import $axios from 'axios'
import router from '../router'
import store from '../store'
import {getHttpUrl} from './Https'

import { Loading, Message } from 'element-ui'

/******创建axios实例********/
// const $axios = axios.create({
// 	baseURL: process.env.VUE_APP_ROOT_URL
// });

let loading;

/**********拦截器 ===> 请求****************/
$axios.interceptors.request.use(config => {

	loading = Loading.service({
		text: '加载中...',
		background: 'rgba(0, 0, 0, 0.7)',
		spinner: 'el-icon-loading',
		customClass: 'loadCss'
	});

	try {
		config.url = getHttpUrl({
			module: config.data.module,
			url: config.url
		})
	} catch(e) {
		config.url = getHttpUrl({
			module: "",
			url: config.url
		})
	}

	config.data = {
		...config.data,
		token: store.state.token
	}
	if (config.method === 'get') {
		config.params = { ...config.data };
	}

	return config
}, error => {
	loading.close();

	Message.error({
		message: JSON.stringify(error),
		showClose: true,
		duration: 2000
	});

	Promise.reject(error)
});

/**********拦截器 ===> 响应****************/
$axios.interceptors.response.use(
	response => {
		loading.close();

		if (response.status == 200) {
			if (!response.data.meta.success) {
				if (response.data.meta.code == 400) {
					// router.replace({
					// 	path: store.state.loginUrl
					// })
				} else {
					Message.error({
						message: response.data.meta.message,
						showClose: true,
						duration: 2000
					});
				}
			} else
				return response.data.data;
		} else {
			Message.error({
				message: "API接口发生错误",
				showClose: true,
				duration: 2000
			});
		}
	},
	error => {
		loading.close();

		let text = "";

		var res = JSON.parse(JSON.stringify(error)).response;
		// url = JSON.parse(JSON.stringify(error)).config.url;
		if (res) {
			if (res.data) {
				var _data = res.data;
				if (_data.meta.code == 400) {
					//重新登录
					// router.replace({
					// 	path: store.state.loginUrl
					// })
					sessionStorage.clear()
					return Promise.reject(error)
				} else {
					text = _data.meta.message;
				}
			} else {
				text = res.statusText;
			}
		}

		Message.error({
			message: text === "" ? "出现错误" : text,
			showClose: true,
			duration: 0
		});

		return Promise.reject(error)
	}
);

export default $axios
